package com.deltabravomedia.theoldtoad;

import java.io.File;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class Crew extends ListActivity {
	private static final String TAG = "Crew";

	private static final int ACTIVITY_IMAGE=0;

	private ProgressDialog m_ProgressDialog = null; 
    private ArrayList<CrewItem> m_items = null;
    private CrewAdapter m_adapter;
    private Runnable viewItems;
    private Runnable getFiles;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
                
        setContentView(R.layout.listview);
        this.setTitle("The Old Toad : Crew");
        m_items = new ArrayList<CrewItem>();
        this.m_adapter = new CrewAdapter(this, R.layout.crewrow, m_items);
                setListAdapter(this.m_adapter);
        
        viewItems = new Runnable(){
            @Override
            public void run() {
                getItems();
            }
        };
        
        Thread thread =  new Thread(null, viewItems, "MagentoBackground");
        thread.start();
        m_ProgressDialog = ProgressDialog.show(Crew.this,    
              "Please wait...", "Retrieving data ...", true);
    }

	@Override
    protected void onListItemClick (ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        
        String fileName = "Crew" + 
        		m_items.get(position).getName().replaceAll("\\W", "").trim();
        fileName = this.getFilesDir() + "/" + fileName;
        
        File file = new File(fileName);
        if (file.length() > 0) {
            Intent i = new Intent(this, Image.class);
            i.putExtra("fileName", fileName);
            i.putExtra("title", "The Old Toad : Crew : " + m_items.get(position).getName());
            startActivityForResult(i, ACTIVITY_IMAGE);
        }
        else
        {
        	Log.w(TAG, "No image file: " + fileName);
        }
	}
    
    private Runnable returnRes = new Runnable() {
        @Override
        public void run() {
            if(m_items != null && m_items.size() > 0){
                m_adapter.notifyDataSetChanged();
                for(int i=0;i<m_items.size();i++)
                m_adapter.add(m_items.get(i));
            }
            m_ProgressDialog.dismiss();
            m_adapter.notifyDataSetChanged();
        }
    };
    
    private class CrewAdapter extends ArrayAdapter<CrewItem> {

        private ArrayList<CrewItem> items;

        public CrewAdapter(Context context, int textViewResourceId, ArrayList<CrewItem> items) {
	        super(context, textViewResourceId, items);
	        this.items = items;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			if (view == null) {
			    LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			    view = vi.inflate(R.layout.crewrow, null);
			}
			CrewItem item = items.get(position);
			if (item != null) {
		        TextView nameText = (TextView) view.findViewById(R.id.nametext);
		        if (nameText != null) {
		              nameText.setText( item.getName());   
		        }
		        TextView ageText = (TextView) view.findViewById(R.id.agetext);
		        if (ageText != null) {
		              ageText.setText( "Age: " + item.getAge());   
		        }
		        TextView hometownText = (TextView) view.findViewById(R.id.hometowntext);
		        if (hometownText != null) {
		              hometownText.setText( "Hometown: " + item.getHometown());   
		        }
		        TextView educationText = (TextView) view.findViewById(R.id.educationtext);
		        if (educationText != null) {
		              educationText.setText( "Education: " + item.getEducation());   
		        }
		        TextView familyText = (TextView) view.findViewById(R.id.familytext);
		        if (familyText != null) {
		              familyText.setText( "Family: " + item.getFamily());   
		        }
		        TextView favdrinkText = (TextView) view.findViewById(R.id.favdrinktext);
		        if (favdrinkText != null) {
		              favdrinkText.setText( "Favorite Drink: " + item.getFavDrink());   
		        }
		        TextView favfoodText = (TextView) view.findViewById(R.id.favfoodtext);
		        if (favfoodText != null) {
		              favfoodText.setText( "Favorire Food: " + item.getFavFood());   
		        }
		        TextView favteamText = (TextView) view.findViewById(R.id.favteamtext);
		        if (favteamText != null) {
		              favteamText.setText( "Favorite Sports/Teams: " + item.getFavTeam());   
		        }
		        TextView passionsText = (TextView) view.findViewById(R.id.passionstext);
		        if (passionsText != null) {
		              passionsText.setText( "Passions: " + item.getPassions());   
		        }
		        TextView likesText = (TextView) view.findViewById(R.id.likestext);
		        if (likesText != null) {
		              likesText.setText( "Likes: " + item.getLikes());   
		        }
		        TextView dislikesText = (TextView) view.findViewById(R.id.dislikestext);
		        if (dislikesText != null) {
		              dislikesText.setText( "Dislikes: " + item.getDislikes());   
		        }
			}
			return view;
        }
    }
    
    private void getItems(){
    	
    	String jsonString = Utilities.getJsonString(TAG, Utilities.GET_CREW_URL, this);

    	JSONObject json;
		try {
			json = new JSONObject(jsonString);
        
	        if (json.has("Crew")) {
	        	JSONArray starters = json.getJSONArray("Crew");

	        	m_items = new ArrayList<CrewItem>();
	
	        	for (int i = 0; i < starters.length(); i++ ){
	        		JSONObject jsonStarter = starters.getJSONObject(i);
	        		CrewItem item = new CrewItem(jsonStarter.getString("name"), jsonStarter.getString("age"), 
	        				jsonStarter.getString("hometown"), jsonStarter.getString("education"),
	        				jsonStarter.getString("family"), jsonStarter.getString("favDrink"),
	        				jsonStarter.getString("favFood"), jsonStarter.getString("favTeam"),
	        				jsonStarter.getString("passions"), jsonStarter.getString("likes"),
	        				jsonStarter.getString("dislikes"));

	        		final String fileName = "Crew" + jsonStarter.getString("name").trim()
    					.replaceAll("\\W", "");
        			
        	        getFiles = new Runnable(){
        	            @Override
        	            public void run() {
        	            	getFile(fileName);	
        	            }
        	        };
        	        
        	        Thread thread =  new Thread(null, getFiles, "MagentoBackground");
        	        thread.start();	
	        		
	        		m_items.add(item);	        		
	        	}
	        }
		} catch (JSONException e) {
			Log.w(TAG, e.getMessage());
		}
        
		Log.i("ARRAY", ""+ m_items.size());
		  
		runOnUiThread(returnRes);
    }
    
	protected void getFile(String fileName) {
		Utilities.getFileFromServer(fileName, this);
	}
}